
import eventBus from '@/Util/EventBus';
import * as PIXI from 'pixi.js'
const TextureCache = PIXI.utils.TextureCache

export interface TimerProps {
    baseContainer: PIXI.Container;
    scaleSize: number;
    posX: number;
    posY: number;
}

export class Timer {
    timer: NodeJS.Timer;
    private timerContainer: PIXI.Container = new PIXI.Container()
    private timerText: PIXI.Text;
    timerSprite: PIXI.Sprite;
    props: TimerProps;
    constructor(props: TimerProps) {
        this.props = props
        props.baseContainer.addChild(this.timerContainer)
        this.createTimer()
    }
    
    hidden(){
        this.timerContainer.visible = false
    }

    createTimer() {
        this.endInterVal()
        this.timerSprite = new PIXI.Sprite(TextureCache['timer'])

        this.timerText = new PIXI.Text('', {
            fontFamily: "黑体",
            fill: '#f0601e',
            fontSize: 25,
            align: "center",
            dropShadow: true,
            fontWeight: 'bold',
            dropShadowColor: "#f29a75",
            dropShadowBlur: 4,
            dropShadowAngle: Math.PI / 2,
            dropShadowDistance: 2,
        }) as PIXI.Text;
        this.timerContainer.scale.set(0.7 * this.props.scaleSize)
        this.setTimerText('20')
        this.timerSprite.addChild(this.timerText)
        this.timerContainer.addChild(this.timerSprite)
        this.timerContainer.x = this.props.posX
        this.timerContainer.y = this.props.posY
    }

    endInterVal() {
        this.setTimerText('20')
        this.timerContainer.visible = false
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = null
        }
    }

    startInterVal(overTimeHandler?: Function, needAlert?: boolean) {
        this.timerContainer.visible = true
        let outCardTime = 20
        let isAlert = false
        this.timer = setInterval(() => {
            outCardTime -= 1
            if (outCardTime < 5 && !isAlert && needAlert) {
                isAlert = true
                eventBus.emit('timerAlert') // 闹钟提示音
            }
            if (outCardTime === -1) {
                overTimeHandler && overTimeHandler()
            } else if (outCardTime >= 0) {
                this.setTimerText(outCardTime)
            }
        }, 1000)
    }

    setTimerText(newText: string | number) {
        if (this.timerText) {
            this.timerText.text = newText
            this.timerText.x = (this.timerSprite.width - this.timerText.width) / 2
            this.timerText.y = (this.timerSprite.height - this.timerText.height) / 2 + 3
        }
    }
}